/**
 * 动态工具URL组件
 * 处理服务端和客户端的URL生成
 */

'use client'

import { useEffect, useState } from 'react'

interface DynamicToolUrlProps {
  toolId: string
  deployPath?: string
  fallbackUrl?: string
  children: (url: string) => React.ReactNode
}

export function DynamicToolUrl({ 
  toolId, 
  deployPath, 
  fallbackUrl, 
  children 
}: DynamicToolUrlProps) {
  const [toolUrl, setToolUrl] = useState<string>(fallbackUrl || '')
  
  useEffect(() => {
    // 在客户端动态生成URL
    if (typeof window !== 'undefined') {
      const baseUrl = window.location.origin
      
      if (deployPath) {
        // 使用部署路径
        const path = deployPath.startsWith('/') ? deployPath : `/${deployPath}`
        setToolUrl(`${baseUrl}${path}`)
      } else {
        // 使用工具页面路径
        setToolUrl(`${baseUrl}/tools/deployed/${toolId}`)
      }
    }
  }, [toolId, deployPath])
  
  return <>{children(toolUrl)}</>
}

/**
 * 动态工具链接组件
 */
interface DynamicToolLinkProps {
  toolId: string
  deployPath?: string
  fallbackUrl?: string
  className?: string
  children: React.ReactNode
  target?: string
  rel?: string
}

export function DynamicToolLink({
  toolId,
  deployPath,
  fallbackUrl,
  className,
  children,
  target = '_blank',
  rel = 'noopener noreferrer'
}: DynamicToolLinkProps) {
  return (
    <DynamicToolUrl
      toolId={toolId}
      deployPath={deployPath}
      fallbackUrl={fallbackUrl}
    >
      {(url) => (
        <a
          href={url}
          target={target}
          rel={rel}
          className={className}
        >
          {children}
        </a>
      )}
    </DynamicToolUrl>
  )
}

/**
 * 服务端安全的URL显示组件
 */
interface SafeToolUrlDisplayProps {
  toolId: string
  deployPath?: string
  fallbackUrl?: string
  className?: string
}

export function SafeToolUrlDisplay({
  toolId,
  deployPath,
  fallbackUrl,
  className
}: SafeToolUrlDisplayProps) {
  return (
    <DynamicToolUrl
      toolId={toolId}
      deployPath={deployPath}
      fallbackUrl={fallbackUrl}
    >
      {(url) => (
        <span className={className}>
          {url || '正在加载...'}
        </span>
      )}
    </DynamicToolUrl>
  )
}
